﻿using Hydrogen.Cmd.Interfaces;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;

namespace Hydrogen.Cmd.Commands
{
    [CommandFlag("p2j", "png2jpg")]
    class Png2JpgCommand : CommandBase
    {
        public static new string Discription
        {
            get
            {
                string description = @"xxx -> jpg
                    【设置转换品质】-q 95   最高100最小1
                    【转换目录下某类文件】-sp *a.png -q 95
                    【转换目录下的全部 png 文件】-q 95";
                return description;
            }
        }
        public override void Invoke(params string[] args)
        {
            //long quality = 95L;
            //string searchPattern = "*.png";
            //if (args.Length > 1) searchPattern = args[1];
            //if (args.Length > 2 && long.TryParse(args[2], out quality)) { }

            Dictionary<string, string> argsDic = GetArgsDic(args, out List<string> oldArgsGroup);

            string qualityStr = GetArgs(argsDic, "-q", "95");
            long quality = 95L; long.TryParse(qualityStr, out quality);
            string searchPattern = GetArgs(argsDic, "-sp", "*.png");



            var dir = Environment.CurrentDirectory;

            var files = Directory.GetFiles(dir, searchPattern, SearchOption.TopDirectoryOnly);


            //foreach (var item in files)
            //for (int i = 0; i < files.Length; i++)
            //{
            //    try
            //    {
            //        Do(files[i], quality);
            //        Console.ConsoleLog.Log("Complate [{0}/{1}]", i + 1, files.Length);
            //    }
            //    catch (Exception ex)
            //    {
            //        Console.ConsoleLog.LogError(ex.ToString());
            //    }
            //}
            Do(files, quality, (index, ex) =>
            {
                if (ex == null) Console.ConsoleLog.Log("Complate [{0}/{1}] {2}", index + 1, files.Length, files[index]);
                else Console.ConsoleLog.LogError(ex.ToString());
            });
            Console.ConsoleLog.WriteColorLine("Done.", ConsoleColor.Green);
        }

        private static ImageCodecInfo GetEncoder(ImageFormat format)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                    return codec;
            }
            return null;
        }

        private static void Do(string[] imageNames, long quality = 95L, Action<int, Exception> callback = null)
        {
            Bitmap im = null;

            using (var eps = new EncoderParameters(1))
            {
                eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                var jpsEncodeer = GetEncoder(ImageFormat.Jpeg);

                StringBuilder url = new StringBuilder();
                for (int i = 0; i < imageNames.Length; i++)
                {
                    try
                    {
                        using (im = new Bitmap(imageNames[i]))
                        {
                            url.Clear();
                            url.Append(Path.GetDirectoryName(imageNames[i]));
                            url.Append(@"\");
                            url.Append(Path.GetFileNameWithoutExtension(imageNames[i]));
                            url.Append("_p2j.jpg");

                            im.Save(url.ToString(), jpsEncodeer, eps);
                            callback?.Invoke(i, null);
                        }
                    }
                    catch (Exception ex)
                    {
                        callback?.Invoke(i, ex);
                    }
                }
            }
        }

        private static void Do(EncoderParameters parameters)
        {

        }

        private static void Do(string imageName, long quality = 95L)
        {
            var dir = Path.GetDirectoryName(imageName);
            var file = Path.GetFileNameWithoutExtension(imageName);
            Bitmap im = new Bitmap(imageName);
            //转成jpg
            var eps = new EncoderParameters(1);
            var ep = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            eps.Param[0] = ep;
            var jpsEncodeer = GetEncoder(ImageFormat.Jpeg);
            //保存图片
            var imgurl = string.Format(@"{0}\{1}.jpg", dir, file);
            im.Save(imgurl, jpsEncodeer, eps);
            //释放资源
            im.Dispose();
            ep.Dispose();
            eps.Dispose();
        }
    }
}
